﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using System.Web.Http;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using Google.Protobuf.WellKnownTypes;
using log4net;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.Asn1.X500;
using Org.BouncyCastle.Asn1.X509;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static log4net.Appender.RollingFileAppender;

namespace CloudApiServer.Controllers
{
    /// <summary>
    /// 甘肃医保接口控制器
    /// </summary>
    [RoutePrefix("prd/hsa/hgs")]
    public class FsiApiGanSuController: ApiController
    {
        /*接口*/
        /// <summary>
        /// 医保接口没找到的统一接口返回
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public IHttpActionResult FsiNotFound(HttpRequestMessage request)
        {
            string url = request.RequestUri.ToString();
            string Method = request.Method.ToString();
            string Errnum = LogHelper.GetErrornumber();
            try
            {
                if (string.IsNullOrEmpty(request.Content.ReadAsStringAsync().Result))
                {
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参为空！当前请求入参：" + request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputSignIn>>(request.Content.ReadAsStringAsync().Result);
                    string infno = fsiRequest.infno;
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加！当前请求的接口号：{infno},当前请求入参：" + request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
            }
            catch (JsonReaderException)
            {
                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参格式不正确！服务端无法正常反序列化！请检查入参是否为Json格式！当前请求入参：" + request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且服务端程序处理异常！请联系管理员排查！当前异常提示：{ex.Message},当前请求入参：" + request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);
            }
        }
        /// <summary>
        /// 9001签到
        /// </summary>
        /// <returns></returns>
        [Route("9001")]
        [HttpPost]
        public async Task<IHttpActionResult> signIn(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputSignIn>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string fixmedins_code = fsiRequest.fixmedins_code;
                    string fixmedins_name = fsiRequest.fixmedins_name;
                    string ip = fsiRequest.Input.signIn.ip;
                    string mac = fsiRequest.Input.signIn.mac;
                    string opter_no = fsiRequest.Input.signIn.opter_no;
                    if (string.IsNullOrEmpty(fixmedins_code) || string.IsNullOrEmpty(fixmedins_name) || string.IsNullOrEmpty(ip) || string.IsNullOrEmpty(mac) || string.IsNullOrEmpty(opter_no))
                    {
                        throw new Exception("参数校验失败：传入的机构代码|机构名称|IP|mac|操作员编号为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    string signno = rnd.Next(1000000, 10000000).ToString();
                    string signtime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "INSERT Into  fsi_signinout values(null,@fixmedins_code,@fixmedins_name,@ip,@mac,@opter_no,@sign_no,0,@signinTime,NULL)";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                        cmd.Parameters.AddWithValue("@fixmedins_name", fixmedins_name);
                        cmd.Parameters.AddWithValue("@ip", ip);
                        cmd.Parameters.AddWithValue("@mac", mac);
                        cmd.Parameters.AddWithValue("@opter_no", opter_no);
                        cmd.Parameters.AddWithValue("@sign_no", signno);
                        cmd.Parameters.AddWithValue("@signinTime", signtime);
                        await cmd.ExecuteNonQueryAsync();

                        var FsiHeader = new FsiHeader<outputsignInOut>
                        {
                            output = new outputsignInOut
                            {
                                signinoutb = new signInOut
                                {
                                    sign_no = signno,
                                    sign_time = signtime
                                }
                            },
                            infcode = 0,
                            warn_msg = null,
                            cainfo = null,
                            err_msg = "success",
                            refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                            signtype = null,
                            respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                            inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"

                        };
                        return Json(FsiHeader);
                    }

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 9002签退
        /// </summary>
        /// <returns></returns>
        [Route("9002")]
        [HttpPost]
        public async Task<IHttpActionResult> signOut(HttpRequestMessage request)
        {

            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputSignOut>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string fixmedins_code = fsiRequest.fixmedins_code;
                    string opter_no = fsiRequest.Input.signOut.opter_no;
                    string sign_no = fsiRequest.Input.signOut.sign_no;
                    if (string.IsNullOrEmpty(fixmedins_code) || string.IsNullOrEmpty(sign_no) || string.IsNullOrEmpty(opter_no))
                    {
                        throw new Exception("参数校验失败：传入的机构代码|签到号|操作员编号为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    string siginoutTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_signinout where fixmedins_code=@fixmedins_code and opter_no=@opter_no and sign_no= @sign_no and state=0 ";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                        cmd.Parameters.AddWithValue("@opter_no", opter_no);
                        cmd.Parameters.AddWithValue("@sign_no", sign_no);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            DataTable dt = new DataTable();
                            dt.Load(reader);
                            if (dt.Rows.Count < 1)
                            {
                                throw new Exception($"查询签到表失败：根据传入的机构代码、操作员编号和签到编号未找到签到信息或已是签退状态！当前获取到了{dt.Rows.Count}条有效的签到记录。当前入参：" + request.Content.ReadAsStringAsync().Result);
                            }
                            else
                            {
                                cmd.Parameters.Clear();
                                cmd.CommandText = "update  fsi_signinout set state=1,siginoutTime=@siginoutTime where fixmedins_code=@fixmedins_code and opter_no=@opter_no and sign_no= @sign_no and state=0 ";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                                cmd.Parameters.AddWithValue("@opter_no", opter_no);
                                cmd.Parameters.AddWithValue("@sign_no", sign_no);
                                cmd.Parameters.AddWithValue("@siginoutTime", siginoutTime);
                                await cmd.ExecuteNonQueryAsync();
                                var FsiHeader = new FsiHeader<outputsignInOut>
                                {
                                    output = new outputsignInOut
                                    {
                                        signinoutb = new signInOut
                                        {
                                            sign_time = siginoutTime
                                        }
                                    },
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                };
                                return Json(FsiHeader);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 1101
        /// </summary>
        /// <returns></returns>
        [Route("1101")]
        [HttpPost]
        public async Task<IHttpActionResult> queryPsnInfo(HttpRequestMessage request)
        {
            DataTable dt = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryPsnInfoRequest>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string cert_no;
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign==false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    //电子凭证的时候传certno 身份证号码
                    if (fsiRequest.Input.data.mdtrt_cert_type == "01")
                    {
                        cert_no = fsiRequest.Input.data.certno;
                    }
                    else
                    {
                        cert_no = fsiRequest.Input.data.mdtrt_cert_no;
                    }
                    if (cert_no == "")
                    {
                        cert_no = FsiDatainfo.Defautlcardno;
                        //throw new Exception("未传入人员身份信息！如需测试可输入身份证1获取测试人员信息。");
                    }
                    //else
                    //{
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_PsnInfo where certno=@certno";
                        cmd.Parameters.AddWithValue("@certno", cert_no);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            if (dt.Rows.Count == 1)
                            {
                                List<Idetinfo> list = new List<Idetinfo>();
                                Random rnd = new Random();
                                DateTime dateTime = DateTime.Now;
                                var FsiHeader = new FsiHeader<outputQueryPsnInfo>
                                {
                                    output = new outputQueryPsnInfo
                                    {
                                        baseinfo = new Baseinfo
                                        {
                                            certno = dt.Rows[0]["certno"].ToString(),
                                            psn_no = dt.Rows[0]["psn_no"].ToString(),
                                            gend = dt.Rows[0]["gend"].ToString(),
                                            exp_content = dt.Rows[0]["exp_content"].ToString(),
                                            brdy = dt.Rows[0]["brdy"].ToString(),
                                            naty = dt.Rows[0]["naty"].ToString(),
                                            psn_cert_type = dt.Rows[0]["psn_cert_type"].ToString(),
                                            psn_name = dt.Rows[0]["psn_name"].ToString(),
                                            age = PublicMethod.CalculateAge(Convert.ToDateTime(dt.Rows[0]["brdy"]), dateTime),
                                        },
                                        insuinfo = new List<Insuinfo>
                                        {
                                            new Insuinfo
                                            {
                                                insuplc_admdvs = dt.Rows[0]["insuplc_admdvs"].ToString(),
                                                psn_insu_date = dt.Rows[0]["psn_insu_date"].ToString(),
                                                cvlserv_flag = dt.Rows[0]["cvlserv_flag"].ToString(),
                                                balc = Convert.ToDouble(dt.Rows[0]["balc"]),
                                                emp_name = dt.Rows[0]["emp_name"].ToString(),
                                                psn_type = dt.Rows[0]["psn_type"].ToString(),
                                                psn_insu_stas = dt.Rows[0]["psn_insu_stas"].ToString(),
                                                insutype = dt.Rows[0]["insutype"].ToString(),
                                                paus_insu_date = dt.Rows[0]["paus_insu_date"].ToString()
                                            }
                                        },
                                        idetinfo = list,
                                    },
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                };
                                return Json(FsiHeader);
                            }
                            else
                            {
                                throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dt.Rows.Count}");
                            }
                        }
                    }
                    //}

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }

        }
        /// <summary>
        /// 5206年度费用累计
        /// </summary>
        /// <returns></returns>
        [Route("5206")]
        [HttpPost]
        public async Task<IHttpActionResult> queryFixmedinsPracPsnSum(HttpRequestMessage request)
        {

            DataTable dt = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryFixmedinsPracPsnSum>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string psn_no = fsiRequest.Input.data.psn_no;
                    if (psn_no == "")
                    {
                        throw new Exception("传入的psn_no(人员编号)为空！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_queryfixmedinspracpsnsum where psn_no=@psn_no";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            List<Cuminfo> dataList = new List<Cuminfo>();
                            foreach (DataRow row in dt.Rows)
                            {
                                Cuminfo item = new Cuminfo
                                {
                                    cum_type_code = row["cum_type_code"].ToString(),
                                    year = row["year"].ToString(),
                                    cum = (decimal)row["cum"],
                                    cum_ym = row["cum_ym"].ToString(),
                                    insutype = row["insutype"].ToString()
                                };
                                dataList.Add(item);
                            }
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var FsiHeader = new FsiHeader<outputCuminfo>
                            {
                                output = new outputCuminfo
                                {
                                    cuminfo = dataList
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 2103退款接口
        /// </summary>
        /// <returns></returns>
        [Route("2103")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleRevoke(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleRevokeRequest>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string fixmedins_code = fsiRequest.fixmedins_code;
                    string setl_id = fsiRequest.Input.data.setl_id;
                    string psn_no = fsiRequest.Input.data.psn_no;
                    string mdtrtid = fsiRequest.Input.data.mdtrt_id;
                    if (string.IsNullOrEmpty(fixmedins_code)|| string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(mdtrtid) || string.IsNullOrEmpty(setl_id) )
                    {
                        throw new Exception("参数校验失败：传入的结算id|人员编号||就诊ID为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dtpsninfo = new DataTable();
                    DataTable dt = new DataTable();
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                    await conn.OpenAsync();
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dtpsninfo.Load(reader);
                                if (dtpsninfo.Rows.Count != 1)
                                {
                                    throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            cmd.CommandText = "select * from fsi_order where psn_no=@psn_no and mdtrt_id=@mdtrt_id and setl_id=@setl_id and order_state=1";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            cmd.Parameters.AddWithValue("@mdtrt_id", mdtrtid);
                            cmd.Parameters.AddWithValue("@setl_id", setl_id);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dt.Load(reader);
                                if (dt.Rows.Count != 1)
                                {
                                    throw new Exception($"查询已结算的订单信息表失败！查询到的订单信息总数为：{dt.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }

                            string SettleAccountsAOutput = dt.Rows[0]["SettleAccountsAOutput"].ToString();
                            if (string.IsNullOrEmpty(SettleAccountsAOutput))
                            {
                                throw new Exception($"参数校验失败：根据传入的参数已找到订单但结算信息为空！");
                            }
                            FsiHeader<outputDrugstoreSettleAccountsPreA> FsiHeaderSettleAccountsPreA = JsonConvert.DeserializeObject<FsiHeader<outputDrugstoreSettleAccountsPreA>>(SettleAccountsAOutput);
                            List<Setldetail> list = new List<Setldetail>();
                            list = FsiHeaderSettleAccountsPreA.output.setldetail;
                            List<Setldetail> dataList = new List<Setldetail>();
                            foreach (var item in list)
                            {
                                //序列化基金支付风项
                                setl_proc_info setlinfoexpcontent = new setl_proc_info
                                {
                                    hifpPayInscp = item.fund_payamt,
                                    polItemCode = "LA01",
                                    poolPropSelfpay = 0,
                                    hifpPay = item.fund_payamt
                                };

                                string expcontentJson = JsonConvert.SerializeObject(setlinfoexpcontent);
                                if (item.fund_pay_type== "310200")
                                {
                                    Setldetail setldetail = new Setldetail
                                    {
                                        fund_pay_type = item.fund_pay_type,
                                        fund_payamt = 0 - item.fund_payamt,
                                        setl_proc_info = expcontentJson,
                                        crt_payb_lmt_amt = 0 - item.crt_payb_lmt_amt,
                                        inscp_scp_amt = 0 - item.inscp_scp_amt,
                                        fund_pay_type_name = item.fund_pay_type_name
                                    };
                                    dataList.Add(setldetail);
                                }
                                else
                                {
                                    Setldetail setldetail = new Setldetail
                                    {
                                        fund_pay_type = item.fund_pay_type,
                                        fund_payamt = 0 - item.fund_payamt,
                                        setl_proc_info = null,
                                        crt_payb_lmt_amt = 0 - item.crt_payb_lmt_amt,
                                        inscp_scp_amt = 0 - item.inscp_scp_amt,
                                        fund_pay_type_name = item.fund_pay_type_name
                                    };
                                    dataList.Add(setldetail);
                                }
                            }
                            var FsiHeader = new FsiHeader<outputDrugstoreSettleRevoke>
                            {
                                output = new outputDrugstoreSettleRevoke
                                {
                                    setlinfo = new SetlinfoRevoke
                                    {
                                        setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                        cvlserv_pay = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.cvlserv_pay,
                                        hifdm_pay = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.hifdm_pay,
                                        psn_pay = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.psn_cash_pay,
                                        hifmi_pay = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.hifmi_pay,
                                        act_pay_dedc = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.act_pay_dedc,
                                        balc = FsiHeaderSettleAccountsPreA.output.setlinfo.balc + FsiHeaderSettleAccountsPreA.output.setlinfo.acct_pay,
                                        medins_setl_id = $"{fixmedins_code}{dateTime.ToString("yyyyMMddHHmmssffff")}",
                                        acct_mulaid_pay = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.acct_mulaid_pay,
                                        hifob_pay = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.hifob_pay,
                                        oth_pay = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.oth_pay,
                                        medfee_sumamt = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.medfee_sumamt,
                                        hifes_pay = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.hifes_pay,
                                        mdtrt_id = mdtrtid,
                                        acct_pay = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.acct_pay,
                                        fund_pay_sumamt = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.fund_pay_sumamt,
                                        fulamt_ownpay_amt = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.fulamt_ownpay_amt,
                                        setl_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}",
                                        inscp_scp_amt = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.inscp_scp_amt,
                                        maf_pay = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.maf_pay,
                                        clr_optins = $"{fsiRequest.mdtrtarea_admvs.Substring(0, 4)}99",
                                        pool_prop_selfpay = 0- FsiHeaderSettleAccountsPreA.output.setlinfo.pool_prop_selfpay,
                                        hifp_pay = 0- FsiHeaderSettleAccountsPreA.output.setlinfo.hifp_pay,
                                        overlmt_selfpay = 0- FsiHeaderSettleAccountsPreA.output.setlinfo.overlmt_selfpay,
                                        preselfpay_amt = 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.preselfpay_amt
                                    },
                                    setldetail =dataList
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            string JsonString = JsonConvert.SerializeObject(FsiHeader);
                            cmd.Transaction = transaction;
                            try
                            {
                                cmd.CommandText = "update fsi_order  set order_state= @order_state,RevokeInput=@RevokeInput,RevokeOutput=@RevokeOutput,update_time=@update_time where psn_no=@psn_no and mdtrt_id=@mdtrt_id and setl_id=@setl_id and order_state=1";
                                cmd.Parameters.AddWithValue("@order_state", 1);
                                cmd.Parameters.AddWithValue("@RevokeInput", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@RevokeOutput", JsonString);
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrtid);
                                cmd.Parameters.AddWithValue("@setl_id", setl_id);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"退款数据处理失败：更新订单记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_queryfixmedinspracpsnsum  VALUES (@psn_no,@cum_type_code,@year,@cum,@cum_ym,@insutype)";
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@cum_type_code", "S1100");
                                cmd.Parameters.AddWithValue("@year", dateTime.ToString("yyyy"));
                                cmd.Parameters.AddWithValue("@cum", 0 - FsiHeaderSettleAccountsPreA.output.setlinfo.medfee_sumamt);
                                cmd.Parameters.AddWithValue("@cum_ym", dateTime.ToString("yyyyMM"));
                                cmd.Parameters.AddWithValue("@insutype", dtpsninfo.Rows[0]["insutype"]);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"退款数据处理失败：插入费用累计记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            transaction.Commit();
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 3301上传对照
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("3301")]
        [HttpPost]
        public async Task<IHttpActionResult> catalogCompUp(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputCatalogCompUp>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DataCatalogCompUp> list = new List<DataCatalogCompUp>();
                    list = fsiRequest.Input.data;
                    string fixmedins_code = fsiRequest.fixmedins_code;
                    if (string.IsNullOrEmpty(fixmedins_code) || list.Count == 0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|上传商品数组为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    string error = "";
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.Transaction = transaction;
                            foreach (var item in list)
                            {
                                try
                                {
                                    cmd.CommandText = "INSERT INTO fsi_catalogcompup  VALUES (@fixmedins_code, @fixmedins_hilist_id, @fixmedins_hilist_name,@list_type, @med_list_codg, @begndate, @enddate, @aprvno, @dosform, @exct_cont, @item_cont, @prcunt, @spec, @pacspec, @memo, @scdz, @prdr_name,@create_time)";
                                    cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                                    cmd.Parameters.AddWithValue("@fixmedins_hilist_id", item.fixmedins_hilist_id);
                                    cmd.Parameters.AddWithValue("@fixmedins_hilist_name", item.fixmedins_hilist_name);
                                    cmd.Parameters.AddWithValue("@list_type", item.list_type);
                                    cmd.Parameters.AddWithValue("@med_list_codg", item.med_list_codg);
                                    cmd.Parameters.AddWithValue("@begndate", item.begndate);
                                    cmd.Parameters.AddWithValue("@enddate", item.enddate);
                                    cmd.Parameters.AddWithValue("@aprvno", item.aprvno);
                                    cmd.Parameters.AddWithValue("@dosform", item.dosform);
                                    cmd.Parameters.AddWithValue("@exct_cont", item.exct_cont);
                                    cmd.Parameters.AddWithValue("@item_cont", item.item_cont);
                                    cmd.Parameters.AddWithValue("@prcunt", item.prcunt);
                                    cmd.Parameters.AddWithValue("@spec", item.spec);
                                    cmd.Parameters.AddWithValue("@memo", item.memo);
                                    cmd.Parameters.AddWithValue("@scdz", item.scdz);
                                    cmd.Parameters.AddWithValue("@prdr_name", item.prdr_name);
                                    cmd.Parameters.AddWithValue("@create_time", createTime);
                                    await cmd.ExecuteNonQueryAsync();
                                    cmd.Parameters.Clear();
                                }
                                catch (Exception ex)
                                {
                                    error = error + $"【{item.fixmedins_hilist_name}/{item.spec}/{item.prcunt}/{item.prdr_name}/{item.aprvno}】上传出错：" + ex.Message + "|";
                                }
                                cmd.Parameters.Clear();
                            }
                            if (error != "")
                            {
                                transaction.Rollback();
                                throw new Exception(error);

                            }
                            else
                            {
                                transaction.Commit();
                                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                                {
                                    output = null,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                };
                                return Json(FsiHeader);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 3302上传撤销
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("3302")]
        [HttpPost]
        public async Task<IHttpActionResult> deleteCatalogCompAudited(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDeleteCatalogCompAudited>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string fixmedins_code = fsiRequest.Input.data.fixmedins_code;
                    string fixmedins_hilist_id = fsiRequest.Input.data.fixmedins_hilist_id;
                    string med_list_codg = fsiRequest.Input.data.med_list_codg;

                    if (string.IsNullOrEmpty(fixmedins_code) || string.IsNullOrEmpty(fixmedins_hilist_id) || string.IsNullOrEmpty(med_list_codg))
                    {
                        throw new Exception("参数校验失败：传入的机构代码|医疗机构内部编码|医保国家编码为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_catalogcompup where fixmedins_code=@fixmedins_code and fixmedins_hilist_id=@fixmedins_hilist_id ";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fixmedins_hilist_id);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            DataTable dt = new DataTable();
                            dt.Load(reader);
                            if (dt.Rows.Count < 1)
                            {
                                throw new Exception($"查询商品上传记录表失败：根据传入的机构代码、医疗机构内部编码未找商品已上传记录！当前入参：" + request.Content.ReadAsStringAsync().Result);
                            }
                            else
                            {
                                cmd.Parameters.Clear();
                                cmd.CommandText = "delete from fsi_catalogcompup where fixmedins_code=@fixmedins_code and fixmedins_hilist_id=@fixmedins_hilist_id  ";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fixmedins_hilist_id);
                                await cmd.ExecuteNonQueryAsync();
                                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                                {
                                    output = null,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                };
                                return Json(FsiHeader);

                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 1317上传信息查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("1317")]
        [HttpPost]
        public async Task<IHttpActionResult> queryMedListMapByPage(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryMedListMapByPageRequest>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string fixmedins_code = fsiRequest.Input.data.fixmedins_code;
                    string medins_list_codg = fsiRequest.Input.data.medins_list_codg;//定点医药机构目录编号
                    string medins_list_name = fsiRequest.Input.data.medins_list_name;//定点医药机构目录名称
                    string med_list_codg = fsiRequest.Input.data.med_list_codg;//医疗目录编码
                    int page_num = fsiRequest.Input.data.page_num;//当前页
                    int page_size = fsiRequest.Input.data.page_size;//本页数据
                    if (string.IsNullOrEmpty(fixmedins_code) || page_num==0|| page_size==0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|当前页码|当前页条数为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    if (string.IsNullOrEmpty(medins_list_codg))
                    {
                        medins_list_codg = "%";
                    }
                    if (string.IsNullOrEmpty(medins_list_name))
                    {
                        medins_list_name = "%";
                    }
                    if (string.IsNullOrEmpty(med_list_codg))
                    {
                        med_list_codg = "%";
                    }
                    int now_page = (page_num-1) * page_size;
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_catalogcompup where fixmedins_code=@fixmedins_code and fixmedins_hilist_id like @medins_list_codg and fixmedins_hilist_name like @medins_list_name and med_list_codg like @med_list_codg limit @nowpage,@pagesize";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                        cmd.Parameters.AddWithValue("@medins_list_codg", "%" + medins_list_codg+ "%");
                        cmd.Parameters.AddWithValue("@medins_list_name", "%" + medins_list_name + "%");
                        cmd.Parameters.AddWithValue("@med_list_codg", "%" + med_list_codg + "%");
                        cmd.Parameters.AddWithValue("@nowpage", now_page);
                        cmd.Parameters.AddWithValue("@pagesize", page_size);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            DataTable dt = new DataTable();
                            List<DataQueryMedListMapByPage> dataList = new List<DataQueryMedListMapByPage>();
                            dt.Load(reader);
                            cmd.Parameters.Clear();
                            foreach (DataRow row in dt.Rows)
                            {
                                DataQueryMedListMapByPage item = new DataQueryMedListMapByPage
                                {
                                    fixmedins_code = row["fixmedins_code"].ToString(),
                                    medins_list_codg = row["fixmedins_hilist_id"].ToString(),
                                    medins_list_name = row["fixmedins_hilist_name"].ToString(),
                                    insu_admdvs = fsiRequest.mdtrtarea_admvs.ToString(),
                                    list_type = row["list_type"].ToString(),
                                    med_list_codg = row["med_list_codg"].ToString(),
                                    begndate = row["begndate"].ToString(),
                                    enddate = row["enddate"].ToString(),
                                    aprvno = row["aprvno"].ToString(),
                                    dosform = row["dosform"].ToString(),
                                    exct_cont = row["exct_cont"].ToString(),
                                    item_cont = row["item_cont"].ToString(),
                                    prcunt = row["prcunt"].ToString(),
                                    spec = row["spec"].ToString(),
                                    pacspec = row["pacspec"].ToString(),
                                    memo = row["memo"].ToString(),
                                    updt_time = row["create_time"].ToString(),
                                    crte_time = row["create_time"].ToString()
                                };
                                dataList.Add(item);
                            }
                            FsiHeader<OutputQueryMedListMapByPage> FsiHeader = new FsiHeader<OutputQueryMedListMapByPage>
                            {
                                output = new OutputQueryMedListMapByPage
                                {
                                    data = dataList,
                                    size=1,
                                    startRow=1,
                                    endRow=1,
                                    pageSize=page_size,
                                    pageNum = page_num
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 3201对账汇总
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("3201")]
        [HttpPost]
        public IHttpActionResult stmtTotal(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputStmtTotalRequest>>(request.Content.ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                var FsiHeader = new FsiHeader<OutputStmtTotal>
                {
                    output = new OutputStmtTotal
                    {
                        stmtinfo = new DataStmtTotal
                        {
                            setl_optins = fsiRequest.insuplc_admdvs,
                            stmt_rslt_dscr="",
                            stmt_rslt="0"
                        }
                    },
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"330000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 5301人员慢特病查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("5301")]
        [HttpPost]
        public async Task<IHttpActionResult> queryPsnOpspReg(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    FsiRequestHeader<InputQueryPsnOpspReg> fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryPsnOpspReg>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string psn_no = fsiRequest.Input.data.psn_no;
                    if (string.IsNullOrEmpty(psn_no))
                    {
                        throw new Exception("参数校验失败：传入的人员编号psn_no为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_querypsnopspreg where psn_no=@psn_no";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            DataTable dt = new DataTable();
                            List<FeedetailQueryPsnOpspReg> dataList = new List<FeedetailQueryPsnOpspReg>();
                            dt.Load(reader);
                            cmd.Parameters.Clear();
                            foreach (DataRow row in dt.Rows)
                            {
                                FeedetailQueryPsnOpspReg item = new FeedetailQueryPsnOpspReg
                                {
                                    opsp_dise_code = row["opsp_dise_code"].ToString(),
                                    opsp_dise_name = row["opsp_dise_name"].ToString(),
                                    exp_content = row["exp_content"].ToString(),
                                    begndate = row["begndate"].ToString(),
                                    enddate = row["enddate"].ToString(),
        
                                };
                                dataList.Add(item);
                            }
                            FsiHeader<OutputQueryPsnOpspReg> FsiHeader = new FsiHeader<OutputQueryPsnOpspReg>
                            {
                                output = new OutputQueryPsnOpspReg
                                {
                                    feedetail = dataList,
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        
        /// <summary>
        /// 2101
        /// </summary>
        /// <returns></returns>
        [Route("2101")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleAccountsPre(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DrugdetailDrugstoreSettleAccountsPreA> list = new List<DrugdetailDrugstoreSettleAccountsPreA>();
                    list = fsiRequest.Input.drugdetail;
                    string psn_no = fsiRequest.Input.druginfo.psn_no;
                    Console.WriteLine(request.Content.ReadAsStringAsync().Result);
                    if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || list.Count == 0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|人员编号|待结算的商品数组为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dtpsninfo = new DataTable();
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dtpsninfo.Load(reader);
                                if (dtpsninfo.Rows.Count != 1)
                                {
                                    throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            string clr_type = "11";
                            if (fsiRequest.Input.druginfo.med_type == "41")
                            {
                                clr_type = "41";
                            }
                            else
                            {
                                clr_type = "11";
                            }
                            string mdtrt_id = rnd.Next(10000000, 90000000).ToString();
                            List<Detlcutinfo> dataList = new List<Detlcutinfo>();
                            foreach (var item in list)
                            {
                                if (fsiRequest.Input.druginfo.med_type != "41"&& fsiadmvs=="33")
                                {
                                    cmd.CommandText = "SELECT * FROM fsi_prescription_detail a  left JOIN fsi_prescription b  on a.auth_rxno = b.auth_rxno where b.hi_rxno =@hi_rxno  and a.med_list_codg=@med_list_codg ";
                                    cmd.Parameters.AddWithValue("@hi_rxno", item.rxno);
                                    cmd.Parameters.AddWithValue("@med_list_codg", item.med_list_codg);
                                    using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                                    {
                                        DataTable dt = new DataTable();
                                        dt.Load(reader);
                                        if (dt.Rows.Count < 1)
                                        {
                                            throw new Exception($"处方药品明细校验失败：【{item.med_list_codg}】商品不存于处方【{item.rxno}】中。");
                                        }
                                    }
                                    cmd.Parameters.Clear();
                                }
                                Detlcutinfo detlcutinfo = new Detlcutinfo
                                {
                                    bas_medn_flag = "0",
                                    med_chrgitm_type = "09",
                                    det_item_fee_sumamt = item.det_item_fee_sumamt,
                                    hi_nego_drug_flag = "0",
                                    fulamt_ownpay_amt = 0,
                                    cnt = item.cnt,
                                    pric = item.pric,
                                    feedetl_sn = item.feedetl_sn,
                                    inscp_scp_amt = item.det_item_fee_sumamt,
                                    drt_reim_flag = "0",
                                    overlmt_amt = 0,
                                    pric_uplmt_amt = item.det_item_fee_sumamt,
                                    selfpay_prop = 0,
                                    preselfpay_amt = 0,
                                    chrgitm_lv = "03"
                                };
                                dataList.Add(detlcutinfo);
                            }
                            List<Setldetail> setldetail = new List<Setldetail>();
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310200",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险个人账户基金"
                                };
                                setldetail.Add(detail);
                            }
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310100",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险统筹基金"
                                };
                                setldetail.Add(detail);
                            }
                            var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                            {
                                output = new outputDrugstoreSettleAccountsPreA
                                {
                                    detlcutinfo = dataList,
                                    setlinfo = new Setlinfo
                                    {
                                        setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                        cvlserv_pay = FsiDatainfo.cvlserv_pay,//公务员医疗补助资金
                                        hifdm_pay = FsiDatainfo.hifdm_pay,//伤残人员医疗保障基金支出
                                        cvlserv_flag = dtpsninfo.Rows[0]["cvlserv_flag"].ToString(),//公务员标志
                                        med_type = fsiRequest.Input.druginfo.med_type,
                                        brdy = dtpsninfo.Rows[0]["brdy"].ToString(),
                                        naty = dtpsninfo.Rows[0]["naty"].ToString(),//民族

                                        psn_cash_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2),//现金支付

                                        certno = dtpsninfo.Rows[0]["certno"].ToString(),//身份证号码
                                        hifmi_pay = FsiDatainfo.hifmi_pay,//居民大病保险资金支出
                                        psn_no = fsiRequest.Input.druginfo.psn_no,
                                        act_pay_dedc = FsiDatainfo.act_pay_dedc,//实际支付起付线
                                        mdtrt_cert_type = fsiRequest.Input.druginfo.mdtrt_cert_type,

                                        balc = Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2),
                                        medins_setl_id = $"{fsiRequest.fixmedins_code}{dateTime.ToString("yyyyMMddHHmmssffff")}",
                                        psn_cert_type = dtpsninfo.Rows[0]["psn_cert_type"].ToString(),
                                        acct_mulaid_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2),//个人账户共济支付金额
                                        clr_way = "1",
                                        hifob_pay = FsiDatainfo.hifob_pay,//职工大额医疗费用补助基金支出
                                        oth_pay = FsiDatainfo.oth_pay,//其他支出
                                        medfee_sumamt = fsiRequest.Input.druginfo.medfee_sumamt,
                                        hifes_pay = FsiDatainfo.hifes_pay,//企业补充医疗保险基金支出
                                        gend = dtpsninfo.Rows[0]["gend"].ToString(),
                                        mdtrt_id = mdtrt_id,

                                        acct_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),//个人账户支出

                                        fund_pay_sumamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),//基金支付

                                        fulamt_ownpay_amt = FsiDatainfo.fulamt_ownpay_amt,//全自费金额
                                        hosp_part_amt = FsiDatainfo.hosp_part_amt,//医院负担金额
                                        inscp_scp_amt = FsiDatainfo.inscp_scp_amt,//符合政策范围金额
                                        insutype = fsiRequest.Input.druginfo.insutype,
                                        maf_pay = FsiDatainfo.maf_pay, //医疗救助基金支出
                                        psn_name = dtpsninfo.Rows[0]["psn_name"].ToString(),
                                        psn_part_amt = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //个人负担总额
                                        clr_optins = null,
                                        pool_prop_selfpay = FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支付比例
                                        psn_type = dtpsninfo.Rows[0]["psn_type"].ToString(),
                                        hifp_pay = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支出
                                        overlmt_selfpay = FsiDatainfo.overlmt_selfpay, //超限价金额
                                        preselfpay_amt = FsiDatainfo.preselfpay_amt, //先行自付金额
                                        age = PublicMethod.CalculateAge(Convert.ToDateTime(dtpsninfo.Rows[0]["brdy"]), dateTime),
                                        clr_type = clr_type,
                                    },
                                    setldetail = setldetail
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            string JsonString = JsonConvert.SerializeObject(FsiHeader);
                            cmd.Transaction = transaction;
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_order  VALUES (null, @fixmedins_code,@fixmedins_name,@order_state,@med_type,@psn_no,@setl_id,@mdtrt_id, @SettleAccountspreAInput,@SettleAccountspreAOutput,@SettleAccountsAInput,@SettleAccountsAOutput,@RevokeInput,@RevokeOutput,@create_time,@update_time)";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                                cmd.Parameters.AddWithValue("@order_state", 0);
                                cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.druginfo.med_type);
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@setl_id", "");
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@SettleAccountspreAInput", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@SettleAccountspreAOutput", JsonString);
                                cmd.Parameters.AddWithValue("@SettleAccountsAInput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountsAOutput", "");
                                cmd.Parameters.AddWithValue("@RevokeInput", "");
                                cmd.Parameters.AddWithValue("@RevokeOutput", "");
                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"预结算处理失败：插入订单记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            transaction.Commit();
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 2102
        /// </summary>
        /// <returns></returns>
        [Route("2102")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleAccounts(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DrugdetailDrugstoreSettleAccountsPreA> list = new List<DrugdetailDrugstoreSettleAccountsPreA>();
                    list = fsiRequest.Input.drugdetail;
                    string psn_no = fsiRequest.Input.druginfo.psn_no;
                    if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || list.Count == 0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|人员编号|待结算的商品数组为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dtpsninfo = new DataTable();
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dtpsninfo.Load(reader);
                                if (dtpsninfo.Rows.Count != 1)
                                {
                                    throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            string clr_type = "11";
                            if (fsiRequest.Input.druginfo.med_type == "41")
                            {
                                clr_type = "41";
                            }
                            else
                            {
                                clr_type = "11";
                            }

                            List<Detlcutinfo> dataList = new List<Detlcutinfo>();
                            foreach (var item in list)
                            {
                                Detlcutinfo detlcutinfo = new Detlcutinfo
                                {
                                    bas_medn_flag = "0",
                                    med_chrgitm_type = "09",
                                    det_item_fee_sumamt = item.det_item_fee_sumamt,
                                    hi_nego_drug_flag = "0",
                                    fulamt_ownpay_amt = 0,
                                    cnt = item.cnt,
                                    pric = item.pric,
                                    feedetl_sn = item.feedetl_sn,
                                    inscp_scp_amt = item.det_item_fee_sumamt,
                                    drt_reim_flag = "0",
                                    overlmt_amt = 0,
                                    pric_uplmt_amt = item.det_item_fee_sumamt,
                                    selfpay_prop = 0,
                                    preselfpay_amt = 0,
                                    chrgitm_lv = "03"
                                };
                                dataList.Add(detlcutinfo);
                            }
                            //序列化拓展字段
                            Setlinfoexpcontent setlinfoexpcontent = new Setlinfoexpcontent
                            {
                                clcYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.clcYearAcctPay, 2),
                                Q0001 = 0,
                                crtYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.crtYearAcctPay, 2)
                            };
                            string expcontentJson = JsonConvert.SerializeObject(setlinfoexpcontent);
                            string mdtrt_id;
                            string setl_id;
                            mdtrt_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                            setl_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                            List<Setldetail> setldetail = new List<Setldetail>();
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310200",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险个人账户基金"
                                };
                                setldetail.Add(detail);
                            }
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310100",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险统筹基金"
                                };
                                setldetail.Add(detail);
                            }
                            //Setldetail detail1 = new Setldetail
                            //{
                            //    fund_pay_type = "650102",
                            //    fund_payamt = 11,
                            //    setl_proc_info = null,
                            //    crt_payb_lmt_amt = 0,
                            //    inscp_scp_amt = 0,
                            //    fund_pay_type_name = "罕见病用药"
                            //};
                            //setldetail.Add(detail1);
                            var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                            {
                                output = new outputDrugstoreSettleAccountsPreA
                                {
                                    detlcutinfo = dataList,
                                    setlinfo = new Setlinfo
                                    {
                                        setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                        cvlserv_pay = FsiDatainfo.cvlserv_pay,//公务员医疗补助资金
                                        hifdm_pay = FsiDatainfo.hifdm_pay,//伤残人员医疗保障基金支出
                                        cvlserv_flag = dtpsninfo.Rows[0]["cvlserv_flag"].ToString(),//公务员标志
                                        med_type = fsiRequest.Input.druginfo.med_type,
                                        exp_content = expcontentJson,
                                        brdy = dtpsninfo.Rows[0]["brdy"].ToString(),
                                        naty = dtpsninfo.Rows[0]["naty"].ToString(),//民族
                                        psn_cash_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2),//现金支付
                                        certno = dtpsninfo.Rows[0]["certno"].ToString(),//身份证号码
                                        hifmi_pay = FsiDatainfo.hifmi_pay,//居民大病保险资金支出
                                        psn_no = fsiRequest.Input.druginfo.psn_no,
                                        act_pay_dedc = FsiDatainfo.act_pay_dedc,//实际支付起付线
                                        mdtrt_cert_type = fsiRequest.Input.druginfo.mdtrt_cert_type,

                                        balc = Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2),
                                        medins_setl_id = $"{fsiRequest.fixmedins_code}{dateTime.ToString("yyyyMMddHHmmssffff")}",
                                        psn_cert_type = dtpsninfo.Rows[0]["psn_cert_type"].ToString(),
                                        acct_mulaid_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2),//个人账户共济支付金额
                                        clr_way = "1",
                                        hifob_pay = FsiDatainfo.hifob_pay,//职工大额医疗费用补助基金支出
                                        oth_pay = FsiDatainfo.oth_pay,//其他支出
                                        medfee_sumamt = fsiRequest.Input.druginfo.medfee_sumamt,
                                        hifes_pay = FsiDatainfo.hifes_pay,//企业补充医疗保险基金支出
                                        gend = dtpsninfo.Rows[0]["gend"].ToString(),
                                        mdtrt_id = mdtrt_id,
                                        acct_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),//个人账户支出
                                        fund_pay_sumamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),//基金支付
                                        fulamt_ownpay_amt = FsiDatainfo.fulamt_ownpay_amt,//全自费金额
                                        hosp_part_amt = FsiDatainfo.hosp_part_amt,//医院负担金额
                                        setl_id = setl_id,
                                        inscp_scp_amt = FsiDatainfo.inscp_scp_amt,//符合政策范围金额
                                        insutype = fsiRequest.Input.druginfo.insutype,
                                        maf_pay = FsiDatainfo.maf_pay, //医疗救助基金支出
                                        psn_name = dtpsninfo.Rows[0]["psn_name"].ToString(),
                                        psn_part_amt = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //个人负担总额
                                        clr_optins = null,
                                        pool_prop_selfpay = FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支付比例
                                        psn_type = dtpsninfo.Rows[0]["psn_type"].ToString(),
                                        hifp_pay = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支出
                                        overlmt_selfpay = FsiDatainfo.overlmt_selfpay, //超限价金额
                                        preselfpay_amt = FsiDatainfo.preselfpay_amt, //先行自付金额
                                        age = PublicMethod.CalculateAge(Convert.ToDateTime(dtpsninfo.Rows[0]["brdy"]), dateTime),
                                        clr_type = clr_type,
                                    },
                                    setldetail = setldetail

                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            string JsonString = JsonConvert.SerializeObject(FsiHeader);
                            cmd.Transaction = transaction;
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_order  VALUES (null, @fixmedins_code,@fixmedins_name,@order_state,@med_type,@psn_no,@setl_id,@mdtrt_id, @SettleAccountspreAInput,@SettleAccountspreAOutput,@SettleAccountsAInput,@SettleAccountsAOutput,@RevokeInput,@RevokeOutput,@create_time,@update_time)";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                                cmd.Parameters.AddWithValue("@order_state", 1);
                                cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.druginfo.med_type);
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@setl_id", setl_id);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@SettleAccountspreAInput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountspreAOutput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountsAInput", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@SettleAccountsAOutput", JsonString);
                                cmd.Parameters.AddWithValue("@RevokeInput", "");
                                cmd.Parameters.AddWithValue("@RevokeOutput", "");
                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入订单记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_queryfixmedinspracpsnsum  VALUES (@psn_no,@cum_type_code,@year,@cum,@cum_ym,@insutype)";
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@cum_type_code", "S1100");
                                cmd.Parameters.AddWithValue("@year", dateTime.ToString("yyyy"));
                                cmd.Parameters.AddWithValue("@cum", fsiRequest.Input.druginfo.medfee_sumamt);
                                cmd.Parameters.AddWithValue("@cum_ym", dateTime.ToString("yyyyMM"));
                                cmd.Parameters.AddWithValue("@insutype", dtpsninfo.Rows[0]["insutype"]);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入费用累计记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            transaction.Commit();
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }


        /// <summary>
        /// 3101明细审核事前分析
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("3101")]
        [HttpPost]
        public async Task<IHttpActionResult> beforeAnalyze(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputRiskConServiceresult>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string gend = fsiRequest.Input.data.patient_dtos.gend;//性别
                    string patn_id = fsiRequest.Input.data.patient_dtos.patn_id;//人员编号
                    string curr_mdtrt_id = fsiRequest.Input.data.patient_dtos.curr_mdtrt_id;//就诊id

                    List<DatariskConServiceresult> dataList = new List<DatariskConServiceresult>();
                    List<ListRiskConServiceresultFsi_order_dtos> fsi_order_dtos_List = fsiRequest.Input.data.patient_dtos.fsi_encounter_dtos.fsi_order_dtos;
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        foreach (var item in fsi_order_dtos_List)
                        {
                            cmd.CommandText = "select  * from  fsi_riskconserviceproduct where med_list_codg = @med_list_codg ";
                            cmd.Parameters.AddWithValue("@med_list_codg", item.hilist_code);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                DataTable dt = new DataTable();
                                dt.Load(reader);
                                if (dt.Rows.Count >= 1)
                                {
                                    for (int i = 0; i < dt.Rows.Count; i++)
                                    {
                                        List<Judge_result_detail_dtosItem> JudgeresultdetaildtosItem = new List<Judge_result_detail_dtosItem>();
                                        Judge_result_detail_dtosItem Judge_result_detail_dtosItem = new Judge_result_detail_dtosItem
                                        {
                                            vola_item_type = "1",
                                            mdtrt_id = curr_mdtrt_id,
                                            jrd_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            rx_id = item.rx_id,
                                            vola_amt = item.sumamt
                                        };
                                        JudgeresultdetaildtosItem.Add(Judge_result_detail_dtosItem);
                                        DatariskConServiceresult riskConServiceresultInfo = new DatariskConServiceresult
                                        {
                                            judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                            rule_id = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}",
                                            vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                            rule_name = dt.Rows[i]["rule_name"].ToString(),
                                            mdtrt_id = curr_mdtrt_id,
                                            vola_amt_stas = "1",
                                            jr_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            vola_amt = 1,
                                            sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                            vola_cont = dt.Rows[i]["vola_cont"].ToString(),
                                            vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                        };
                                        dataList.Add(riskConServiceresultInfo);
                                    }

                                }
                                dt.Dispose();
                                reader.Close();
                                reader.Dispose();
                            }

                            cmd.Parameters.Clear();
                        }
                    }
                    var FsiHeader = new FsiHeader<OutputriskConService>
                    {
                        output = new OutputriskConService
                        {
                            result = dataList
                        },
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 3102明细审核事中分析
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("3102")]
        [HttpPost]
        public async Task<IHttpActionResult> courseAnalyze(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputRiskConServiceresult>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string gend = fsiRequest.Input.data.patient_dtos.gend;//性别
                    string patn_id = fsiRequest.Input.data.patient_dtos.patn_id;//人员编号
                    string curr_mdtrt_id = fsiRequest.Input.data.patient_dtos.curr_mdtrt_id;//就诊id

                    List<DatariskConServiceresult> dataList = new List<DatariskConServiceresult>();
                    List<ListRiskConServiceresultFsi_order_dtos> fsi_order_dtos_List = fsiRequest.Input.data.patient_dtos.fsi_encounter_dtos.fsi_order_dtos;
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        foreach (var item in fsi_order_dtos_List)
                        {
                            cmd.CommandText = "select  * from  fsi_riskconserviceproduct where med_list_codg = @med_list_codg ";
                            cmd.Parameters.AddWithValue("@med_list_codg", item.hilist_code);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                DataTable dt = new DataTable();
                                dt.Load(reader);
                                if (dt.Rows.Count >= 1)
                                {
                                    for (int i = 0; i < dt.Rows.Count; i++)
                                    {
                                        List<Judge_result_detail_dtosItem> JudgeresultdetaildtosItem = new List<Judge_result_detail_dtosItem>();
                                        Judge_result_detail_dtosItem Judge_result_detail_dtosItem = new Judge_result_detail_dtosItem
                                        {
                                            vola_item_type = "1",
                                            mdtrt_id = curr_mdtrt_id,
                                            jrd_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            rx_id = item.rx_id,
                                            vola_amt = item.sumamt
                                        };
                                        JudgeresultdetaildtosItem.Add(Judge_result_detail_dtosItem);
                                        DatariskConServiceresult riskConServiceresultInfo = new DatariskConServiceresult
                                        {
                                            judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                            rule_id = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}",
                                            vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                            rule_name = dt.Rows[i]["rule_name"].ToString(),
                                            mdtrt_id = curr_mdtrt_id,
                                            vola_amt_stas = "1",
                                            jr_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            vola_amt = 1,
                                            sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                            vola_cont = dt.Rows[i]["vola_cont"].ToString(),
                                            vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                        };
                                        dataList.Add(riskConServiceresultInfo);
                                    }

                                }
                                dt.Dispose();
                                reader.Close();
                                reader.Dispose();
                            }

                            cmd.Parameters.Clear();
                        }
                    }
                    var FsiHeader = new FsiHeader<OutputriskConService>
                    {
                        output = new OutputriskConService
                        {
                            result = dataList
                        },
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
    }
}
